import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View } from '@tarojs/components'
import { connect } from 'react-redux'
import { getAccessId } from '@/store/user/action'
import { initLocation, setOpenLocation, updateCity, updateCurrentLocation } from '@/store/location/action'
import { receiveRedPacket, getReceiveAmount } from '@/api/distribution'
import { concatUrl } from '@/utils'
import classnames from 'classnames'
import './index.scss'
import { getAreaInfo } from '@/api/platform'
import map from '@/utils/map'
import { getNewSessionKey } from '@/utils/auth'



interface State {
  location: IStore | null,
  receive: any,
  status: any,
  loading: any,
  redPacketAmount: any,
  result: any,
  openVisable: any,
  cityCode: any
}

@connect<any>(({ location, user }) => ({ location, user }), _dispatch => ({
  // 缓存 当前区域经纬度，当前区域信息，城市名
  dispatchLocation(params) {
    return _dispatch(initLocation(params))
  },
  // 位置授权状态（true: 已开启，false: 未开启）
  dispatchOpenLocation(status) {
    return _dispatch(setOpenLocation(status))
  },
  dispatchCity(params) {
    return _dispatch(updateCity(params))
  },
  dispatchCurrentLocation(params) {
    return _dispatch(updateCurrentLocation(params))
  },
  dispatchUserInfo() {
    return _dispatch(getAccessId())
  },
}))
class Adviser extends Component<any> {
  $instance = getCurrentInstance();
  constructor (props) {
    super(props)
    this.state = {
      location: null,
      receive: false,
      status: 0,
      loading: false,
      redPacketAmount: 0,
      result: false,
      openVisable: false,
      cityCode: '',
    }
  }
  state: State
  componentDidMount() {
    this.inter()
  }

  UNSAFE_componentWillReceiveProps() {
  }
  inter = () => {
    let { userId } = this.props.user.userInfo
    let _this = this
    if (userId) { // 有登录状态才获取
      _this.getReceiveAmount()
    }
  }
  init = async () => {
    const { dispatchOpenLocation, dispatchCity, dispatchCurrentLocation } = this.props
    let { cityCode } = this.state
    if (cityCode) {
      const { storeCode = '' } = this.$instance.router.params
      let { loading } = this.state
      if (loading) {
        return
      }
      this.setState({
        loading: true,
        cityCode
      }, () => {
        receiveRedPacket({
          storeCode,
          cityCode
        }).then(res => {
          console.log('res', res)
          this.setState({
            loading: false,
            result: true
          }, () => {
            let { redPacketAmount, status } = res.data.data
            this.setState({
              redPacketAmount,
              status
            })
          })
        }).catch(() => {
          this.setState({
            loading: false
          })
        })

      })
    } else {


      let curLocation: any = await map.getLocation(true)
      if (curLocation) {
        dispatchOpenLocation(true)
        if (curLocation) { // latitude维度  longitude经度
          let { latitude, longitude } = curLocation
          let location = `${longitude},${latitude}`
          dispatchCurrentLocation(curLocation)
          // 获取所在位置城市,传递经纬度坐标字符串，用,隔开
          await getAreaInfo({ location }).then(res => {
            let { data } = res?.data
            let { adCode, name, districtCode } = data
            let current = {
              adCode,
              name,
              districtCode,
              latitude,
              longitude
            }
            dispatchCity(current)
            const { storeCode = '' } = this.$instance.router.params
            let cityCode = adCode ? adCode : ''
            let { loading } = this.state
            if (loading) {
              return
            }
            this.setState({
              loading: true,
              cityCode: adCode
            }, () => {
              receiveRedPacket({
                storeCode,
                cityCode
              }).then(res => {
                console.log('res', res)
                this.setState({
                  loading: false,
                  result: true
                }, () => {
                  let { redPacketAmount, status } = res.data.data
                  this.setState({
                    redPacketAmount,
                    status
                  })
                })
              }).catch(() => {
                this.setState({
                  loading: false
                })
              })

            })
          })
        }
      } else { // 没有开启授权，直接拿广州的cityCode
        this.setState({
          openVisable: true
        })
      }
    }

  }

  closeOpenVisable = () => {
    this.setState({
      openVisable: false
    })
  }

  /**
  * 领红包
  **/
  receiveRedpacket(storeCode, cityCode) {
    receiveRedPacket({
      storeCode,
      cityCode
    }).then(res => {
      console.log('res', res)
    })
  }

  /**
  * 获取领红包状态
  **/
  getReceiveAmount() {
    getReceiveAmount().then(res => {
      let { redPacketAmount, status } = res.data.data
      this.setState({
        redPacketAmount,
        status
      })
    })
  }

  open = () => {
    let { userId } = this.props.user.userInfo
    let locationInfo = Taro.getStorageSync('CURRENT_LOCATION_INFO') || {}
    if (!userId) { // 未登录，跳去登录
      const pages = Taro.getCurrentPages()
      const query = pages[pages.length - 1].options
      Taro.setStorageSync('BACK_ROUTE', concatUrl('pages/distribution/redpacket/index', query))
      getNewSessionKey().then(() => { // 跳转过去的必须登录login拿到sessionKey，确保在登录的时候，不会sessionKey过期
        Taro.navigateTo({
          url: '/pages/user/login/index'
        })
      })
      return
    }
    this.init()
  }

  gotoUse() {
    Taro.navigateTo({
      url: '/pages/redpacket/index/index'
    })
  }


  onShareAppMessage() {
    let { storeCode = '' } = this.$instance.router.params
    return {
      title: `集群车宝9周年庆`,
      path: `pages/distribution/redpacket/index?storeCode=${storeCode}`,
    }
  }

  // 开启定位
  openSetting = () => {
    let _this = this
    Taro.openSetting().then(res => {
      const status = res.authSetting['scope.userLocation']
      if (status) {
        console.log('status', status)
        _this.setState({
          openVisable: false
        }, () => {
          _this.open()
        })
      }
    })
  }


  render() {
    const { loading, status, redPacketAmount, result, openVisable } = this.state
    return (
      <View className="container">
        {
          status == 0 ?
            <View className='bottom-box'>
              {
                !loading ? <View className='bottom-txt'>
                  <View>集群车宝9周年庆</View>
                  <View>百万红包免费送，赶紧领取</View>
                </View> :
                  <View className='bottom-txt'>
                    <View style="visibility:hidden;">集群车宝9周年庆</View>
                    <View>马上打开....</View>
                  </View>
              }

              {
                result && <View className='trans light scale'></View>
              }
              <View className='btn-warp'>
                <View className={classnames('bottom-btn', {
                  'open-status': status
                })} onClick={this.open}></View>
              </View>
            </View>
            :
            <View className='bottom-box bottom-box__open trans top'>
              <View className='open-txt'>
                <View>恭喜你，获得红包</View>
                <View><text className='big'>{redPacketAmount}</text>元</View>
              </View>

              <View className='btn-warp'>
                <View className='use-btn' onClick={this.gotoUse}></View>
              </View>
            </View>
        }
        {
          openVisable ? (
            <View className="dialog-wrap" >
              <View className="dialog-bg" onClick={this.closeOpenVisable}></View>
              <View className="dialog-mask">
                {/* <View className="dialog-tips">请先开启定位权限</View> */}
                <View className='dialog-tips'>若小程序定位已开启</View>
                <View className='dialog-tips'>请检查手机 定位服务 是否开启</View>
                <View className='dialog-tips'>请检查应用设置是否授予App 定位 权限</View>
                <View className="open-btn" onClick={this.openSetting}>开启权限</View>
              </View>
            </View>
          ) : null
        }
      </View>
    )
  }
}
export default Adviser
